<?php

namespace app\index\controller;

use app\BaseController;
use app\index\service\WebService;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Session;
use app\index\service\WxLogin;

class WeiXin extends BaseController
{
    public function index() {}

    /**
     * 展示页，点击登录
     * @author  messha1r
     * @date    2025-09-10
     * @param   string $scope    获取用户信息
     * @return  html    
     */
    public function wxLogin(string $scope = 'snsapi_userinfo')
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
        $url .= '?appid=' . $this->appId;

        $return_url = $this->cpolarUrl . '/index/WeiXin/doLogin';
        $return_url = urlencode($return_url);

        $url .= '&redirect_uri=' . $return_url;
        $url .= '&response_type=code&scope=' . $scope;

        $state = rand(100000, 999999) . time();
        Session::set('state', $state);
        $url .= '&state=' . $state;

        $url .= '#wechat_redirect';

        $str = <<<EOF
        <div>
            <a href="{$url}">点击登录</a>
        </div>
EOF;
        return $str;
    }

    /**
     * 网页授权后,以及返回的数据，获取用户信息
     * @author  messha1r
     * @date    2025-09-10
     * @return  string     
     */
    public function doLogin()
    {
        // 返回带有code,state['code'=>'asdgasdgadsgadsgasdg','state'=>'14612461223462346']
        $input = Request::param();
        $state = Session::get('state');
        if ($input['state'] == $state) {
            $web = new WebService();
            $res= $web->getWebAccessToken($input);
            //TODO 把openid存到数据库

            $user = $web->getUserInfo($res['access_token'], $res['openid']);

            $str = <<<EOF
            <div>welcome,{$user['nickname']}，您已登录,您的openid为:{$res['openid']}</div>
EOF;
            return $str;
        } else {
            return 'state不正确，请检查';
        }
    }





    /**
     * 验证signature
     * http://8a7612c.r20.vip.cpolar.cn/index/WeiXin/notifyInfo
     * @author  messha1r
     * @date    2025-09-10
     * @param        
     * @param        
     * @return string 
     */
    public function notifyInfo()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr = $_GET['echostr'];

        $token = $this->token;
        header('Content-Type: ' . 'text/plain');

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            echo $echostr;
            exit;
        } else {
            echo 'failed';
        }
    }
}
